extends Node


# This class is for managing diffrent user data
# e.g : Purchases , Level progress ,coins ...
# All user data should follow key , value dictionary 
# e.g { "key" : "" , "value" : {} }

signal data_changed # Used to update ui when data is changed


var _skins := {
	"key" : "skins",
	"value" : {
		"current" : 1,
		"purchases" : [1,],
	},
	
} setget _set_skins , get_skins

var _score := {
	"key" : "score",
	"value" : {
		"coins" : 50,
		"level" : 1,
	},
} setget _set_score , get_score


var _settings := {
	"key" : "settings",
	"value" : {
		"sound" : true,
		"music" : true,
	},
} setget _set_settings , get_settings

# Called when the node enters the scene tree for the first time.
func _ready():
#	update_score(400,13)
#	update_skins(2,[1,2,3,4])
	_load_user_data()


func update_skins(current : int , purchased : Array) -> void:
	var new_skins_val := {
		"key" : "skins",
		"value" : {
			"current" : current,
			"purchases" : purchased,
		}
		
	}
	_set_skins(new_skins_val, true)


func update_score(coins : int , level : int) -> void:
	var new_score_val := {
		"key" : "score",
		"value" : {
			"coins" : coins,
			"level" : level,
		}
		
	}
	_set_score(new_score_val, true)


func update_settings(sound : bool , music : bool) -> void:
	var new_settings := {
		"key" : "settings",
		"value" : {
			"sound" : sound,
			"music" : music,
		}
		
	}
	_set_settings(new_settings, true)


func get_skins() -> Dictionary:
	return _skins


func get_score() -> Dictionary:
	return _score 


func get_settings() -> Dictionary:
	return _settings


func _set_skins(data : Dictionary , update : bool = false) -> void:
	_skins = data
	if update:
		Utils.save_to_file_async("skins",data)

	#Update global data
	B4DFramework.set_skins_purchased(data.value.purchases)
	B4DFramework.set_skin(data.value.current)



func _set_score(data : Dictionary , update : bool = false) -> void:
	_score = data
	if update:
		Utils.save_to_file_async("score",data)
	
	B4DFramework.set_coins_count(data.value.coins)
	B4DFramework.set_level(data.value.level)
	
	emit_signal("data_changed")


func _set_settings(data : Dictionary , update : bool = false) -> void:
	_settings = data
	if update:
		Utils.save_to_file_async("settings",data)

	#Update global data
	B4DFramework.set_settings(data.value)


func _load_user_data() -> void:
	# Connect to data loading signal callback
	Utils.connect("data_loaded",self,"_on_data_loaded")# Called everytime data is loaded
	
	Utils.read_from_file_async("score") # load score data
	
	Utils.read_from_file_async("skins") # load skins data
	
	Utils.read_from_file_async("settings")


# On data loaded callback
# Called whenever data is successfully loaded from a file
func _on_data_loaded(key : String , value : Dictionary) -> void:
	Utils.debug("_on_data_loaded",1,str(value))
	
	match key:
		"score" :
			_set_score(value)
			emit_signal("data_changed")
		"skins" :
			_set_skins(value)
		"settings" :
			_set_settings(value)


